package parser;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2024年03月29日 19:30
 */
public class PrintDOMParser {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PrintDOMParser.class.getClassLoader().getResourceAsStream("students.xml"));
//            Document document = builder.parse(PrintDOMParser.class.getClassLoader().getResourceAsStream("actions.xml"));
            Element root = document.getDocumentElement();
            print(root);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void print(Element root) {
        // 开始打印开始标签
        System.out.print("<" + root.getTagName());
        // 打印属性
        NamedNodeMap attributes = root.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            System.out.print(" " + attributes.item(i));
        }

        // 开始标签结束
        System.out.print(">");

        // 打印标签体内容
        // 获取所有子节点
        NodeList nodes = root.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            // 不同的节点处理方式也不同
            if (node.getNodeType() == Node.TEXT_NODE) {
                // 如果是文本节点,则直接打印节点内容
                System.out.print(node.getTextContent());
            }
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                // 如果是元素节点,则递归调用
                Element ele = (Element) node;
                print(ele);
            }
        }

        // 打印结束标签
        System.out.print("</" + root.getTagName() + ">");
    }
}
